package com.wuwei.elearning.jobcard;

import com.alibaba.excel.EasyExcel;
import com.spire.doc.*;
import com.spire.doc.collections.ParagraphCollection;
import com.spire.doc.collections.RowCollection;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.documents.Paragraph;
import lombok.SneakyThrows;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理word里面的换行符
 */
@SpringBootTest
public class ConvertWord {
    private String dirPath = "D:\\芜湖钻石\\CBT建设\\工卡";

    @SneakyThrows
    @Test
    public void convert(){
        //获取本目录下所有文件
        List<Path> pathList = Files.list(Paths.get(dirPath)).filter(Files::isRegularFile).collect(Collectors.toList());
        for (Path path : pathList) {
            Path fileName = path.getFileName();
            String filePath = dirPath+"\\"+fileName;
            System.out.println(filePath);

            FileInputStream inputStream = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(inputStream);
            // 获取第二个表格（假设这是你要修改的表格）
            XWPFTable table2 = document.getTables().get(1);
            List<XWPFTableRow> rows = table2.getRows();

            for (int i = 0; i < rows.size(); i++) {
                XWPFTableRow tableRow = rows.get(i);
                XWPFTableCell cell0 = tableRow.getCell(0);
                XWPFTableCell cell1 = tableRow.getCell(1);

                List<XWPFParagraph> paragraphs1 = cell1.getParagraphs();

                List<XWPFParagraph> paragraphs0 = cell0.getParagraphs();
                removeNullPara(paragraphs0,cell0);

                replacePara(paragraphs1,cell1);
            }

            //将修改后的内容写回到文档
            FileOutputStream outputStream = new FileOutputStream(filePath);
            document.write(outputStream);
            outputStream.close();

            // 关闭文档和输入流
            document.close();
            inputStream.close();
        }
    }

    private void replacePara(List<XWPFParagraph> paragraphs, XWPFTableCell cell) {
        for (int i = 0; i < paragraphs.size(); i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            String text = paragraph.getText();
               if (text.length()>2&&text.endsWith("\n")) {
                    // 删除字符串末尾的换行符\n
                    String cleanedText = text.replaceAll("\\n$", "");
                    System.out.println(cleanedText);
                    System.out.println("需要修改该段落");
                    //这里如何把text替换成cleanedText
                    // 获取段落的所有运行对象（文本段落通常只有一个运行对象）
                   PoiUtils.replaceInParagraph(paragraph,text,cleanedText);
                }
        }
    }

    /**
     * 删除表格中的空行
     * @param paragraphs
     */
    private void removeNullPara(List<XWPFParagraph> paragraphs,XWPFTableCell cell) {
        for (int i1 = 0; i1 < paragraphs.size(); i1++) {
            XWPFParagraph paragraph = paragraphs.get(i1);
            String text = paragraph.getText();
            if ("".equals(text)) {
//                System.out.println("需要删除该段落");
//                cell.removeParagraph(i1);
                cell.removeParagraph(i1);
            }
        }
    }

    //设置表格的某一行的高度为4厘米
    @SneakyThrows
    @Test
    public void setH(){
        //获取本目录下所有文件
        List<Path> pathList = Files.list(Paths.get(dirPath)).filter(Files::isRegularFile).collect(Collectors.toList());
        for (Path path : pathList) {
            Path fileName = path.getFileName();
            String filePath = dirPath + "\\" + fileName;
            System.out.println(filePath);

            FileInputStream inputStream = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(inputStream);
            XWPFTable table = document.getTables().get(0);

            XWPFTableRow tableRow = table.getRows().get(15);
            //设置高度为4厘米
            tableRow.setHeight(2300);

            //将修改后的内容写回到文档
            FileOutputStream outputStream = new FileOutputStream(filePath);
            document.write(outputStream);
            outputStream.close();
            // 关闭文档和输入流
            document.close();
            inputStream.close();
        }

    }

    @SneakyThrows
    @Test
    public void rename(){
        //获取本目录下所有文件
        List<Path> pathList = Files.list(Paths.get(dirPath)).filter(Files::isRegularFile).collect(Collectors.toList());
        int index = 1;
        for (Path path : pathList) {
            Path fileName = path.getFileName();
            String filePath = dirPath + "\\" + fileName;

            FileInputStream inputStream = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(inputStream);

            String text = document.getTables().get(0).getRows().get(2).getCell(2).getText();
            inputStream.close();
            String newFileName = dirPath + "\\"+(index)+"-"+text+"-"+fileName;
            index++;
            System.out.println(newFileName);
            //这里如何把新文件命名为newFileName
            // 重命名文件
            Path newFilePath = Paths.get(newFileName);
            Files.move(path, newFilePath);
            System.out.println("File renamed to: " + newFileName);



        }
    }

    /**
     * 设置页眉
     */
    @SneakyThrows
    @Test
    public void setHeader(){
        //获取本目录下所有文件
        List<Path> pathList = Files.list(Paths.get(dirPath)).filter(Files::isRegularFile).collect(Collectors.toList());
        for (Path path : pathList) {
            Path fileName = path.getFileName();
            String filePath = dirPath + "\\" + fileName;
            FileInputStream inputStream = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(inputStream);

            // 获取页眉
            XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document);

            // 获取默认的页眉
            XWPFHeader header = headerFooterPolicy.getDefaultHeader();
            if (header != null) {
                // 处理页眉，例如输出内容或者其他操作
                System.out.println("Default Header content: " + header.getText());
                XWPFTable table = header.getTables().get(0);
                XWPFTableCell cell = table.getRows().get(2).getCell(3);
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    String text = paragraph.getText();
                    if (!"".equals(text)&&text!=null) {
                        PoiUtils.replaceInParagraph(paragraph,text,"日期");
                    }
                }

            } else {
                System.out.println("No default header found.");
            }

            //将修改后的内容写回到文档
            FileOutputStream outputStream = new FileOutputStream(filePath);
            document.write(outputStream);
            outputStream.close();

            // 关闭文档和输入流
            document.close();
            inputStream.close();
        }
   }

    @SneakyThrows
    @Test
    public void getFileName(){
        List<Path> pathList = Files.list(Paths.get(dirPath)).filter(Files::isRegularFile).collect(Collectors.toList());
        List<JobCard> list = new ArrayList<>();

        for (Path path : pathList) {
            Path fileName = path.getFileName();
            String string = fileName.toString();
            int lastIndexOf = string.lastIndexOf("-");
            String substring = string.substring(0, lastIndexOf);
            int indexOfPoint = string.indexOf(".");
            String title = string.substring(lastIndexOf+1,indexOfPoint);
            String cardName = substring.substring(substring.indexOf("-")+1);
            JobCard jobCard = new JobCard();
            jobCard.setTitle(title);
            jobCard.setCardName(cardName);
            list.add(jobCard);
        }

        EasyExcel.write("D:\\芜湖钻石\\CBT建设\\工卡清单.xlsx",JobCard.class).sheet().doWrite(list);
    }
}
